package com.example.imagetest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.VideoView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyVideoActivity extends AppCompatActivity implements View.OnClickListener {

    // UI控件
    private Button button;
    private ImageView control;
    private VideoView videoView;
    private SeekBar seekBar;
    private LinearLayout linearLayout;
    // Handler用于处理定时任务
    private Handler handler = new Handler(Looper.getMainLooper());
    // 日志标签
    public static final String TAG = "VideoActivity";
    // Runnable用于更新SeekBar的进度
    private Runnable updateSeekBar;
    // 视频宽高比
    private float videoAspectRatio = 1.0f;
    // 视频URL
    private static final String url = "https://www.w3schools.com/html/mov_bbb.mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_video);
        Log.e(TAG, "OnCreate ...");
        button = findViewById(R.id.button);
        control = findViewById(R.id.pause);
        seekBar = findViewById(R.id.seekbar);
        videoView = findViewById(R.id.video);
        linearLayout = findViewById(R.id.linearLayout);

        // 调整线性布局，宽度为屏幕宽度一半并居中
        linearLayout.post(() -> {
            ViewGroup.LayoutParams linearLayoutLayoutParams = linearLayout.getLayoutParams();
            linearLayoutLayoutParams.width = (int) (getResources().getDisplayMetrics().widthPixels / 2.1);
            linearLayout.setLayoutParams(linearLayoutLayoutParams);

            FrameLayout.LayoutParams layoutParamsCenter = new FrameLayout.LayoutParams(linearLayout.getLayoutParams());
            layoutParamsCenter.gravity = Gravity.CENTER;
            layoutParamsCenter.topMargin = videoView.getTop() + (int) (videoView.getHeight() / 2.2);
            linearLayout.setLayoutParams(layoutParamsCenter);
        });

        // 设置VideoView的宽度为屏幕一半
        videoView.post(new Runnable() {
            @Override
            public void run() {
                ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
                layoutParams.width = getResources().getDisplayMetrics().widthPixels / 2;
                layoutParams.height = getResources().getDisplayMetrics().heightPixels / 2;
                videoView.setLayoutParams(layoutParams);
            }
        });

        // 动态设置 SeekBar 的宽度为屏幕的三分之一
        seekBar.post(() -> {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) seekBar.getLayoutParams();
            params.width = getResources().getDisplayMetrics().widthPixels / 3;
            seekBar.setLayoutParams(params);
        });

        // 当视频准备好时更新SeekBar的最大值
        // 这里使用lambda表达式替代匿名内部类，匿名内部类是MediaPlayer.OnVideoSizeChangedListener，mp是参数MediaPlayer
        videoView.setOnPreparedListener(mp -> {
            Log.e(TAG, "视频准备好了");
            Log.e(TAG, "更新 SeekBar 的最大值");
            // 设置SeekBar的最大值为视频的持续时间
            seekBar.setMax(videoView.getDuration());

            // 获取视频宽高比
            // 这句代码没有执行，说明OnVideoSizeChanged监听器没有被触发
            mp.setOnVideoSizeChangedListener((mp1, width, height) -> {
                Log.e(TAG, "视频大小：宽度= " + width + "高度= " + height);
                videoAspectRatio = (float) width / height;
                adjustVideoSize();
            });

            // 定期更新 SeekBar 的进度
            updateSeekBar = new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG, "定期更新 SeekBar 的进度");
                    // 获取VideoView的播放位置
                    seekBar.setProgress(videoView.getCurrentPosition());
                    // 将当前的Runnable任务重新添加到Handler消息队列中去，并延迟1000ms
                    // updateSeekbar没秒执行一次，更新一次Seekbar的进度
                    handler.postDelayed(this, 1000);
                }
            };
            handler.post(updateSeekBar);
        });

        // 监听SeekBar的拖动事件以实现快进和快退
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            // 拖动进度条进度改变的时候调用
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    videoView.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 用户开始拖动 SeekBar 时暂停视频
                videoView.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 用户停止拖动 SeekBar 时继续播放视频
                videoView.start();
            }
        });

        // 给按钮和视频绑定单击事件
        button.setOnClickListener(this);
        control.setOnClickListener(this);
        videoView.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button) {
            int videoId = 1;
            downLoadVideos(url, videoId);
        } else if (view.getId() == R.id.pause || view.getId() == R.id.video) {
            // 为控制视频按钮设置单击逻辑
            if (videoView.isPlaying()) {
                // 将视频播放状态该为暂停，同时修改图片
                control.setImageResource(R.drawable.show);
                videoView.pause();
            } else {
                control.setImageResource(R.drawable.pause);
                videoView.start();
            }
        }
    }

    public void downLoadVideos(String url, int videoId) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                Log.e(TAG, String.format("DownLoad Failed %s", videoId));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e(TAG, String.format("DownLoad Failed %s", response));
                    return;
                } else {
                    File videoFile = new File(getExternalFilesDir(null), "download_video.mp4");
                    InputStream inputStream = response.body().byteStream();
                    OutputStream outputStream = new FileOutputStream(videoFile);
                    try {
                        byte[] buffer = new byte[2048];
                        int byteRead;
                        while ((byteRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, byteRead);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "保存图片失败: " + e.getMessage());
                    } finally {
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }

                    File externalFile = new File(Environment.
                            getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
                            , "download_video.mp4");

                    try {
                        copyFile(videoFile, externalFile);
                        Log.e(TAG, "视频文件在安卓机中的存储位置：" + externalFile.getAbsolutePath());
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "拷贝视频文件出现错误");
                    }

                    // 更新UI布局
                    runOnUiThread(() -> {
                        videoView.setVideoURI(Uri.fromFile(videoFile));
                        Log.e(TAG, String.format("uri: %s", Uri.fromFile(videoFile)));
                        videoView.start();
                        // 设置进度条等可见
                        linearLayout.setVisibility(View.VISIBLE);
                        seekBar.setVisibility(View.VISIBLE);
                        control.setVisibility(View.VISIBLE);
                        Log.e(TAG, String.format("Video Download ans set: %s", url));
                    });
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止定时任务，防止内存泄漏
        handler.removeCallbacks(updateSeekBar);
    }

    private void adjustVideoSize() {
        Log.e(TAG, "调整视频的宽高比");

        // 获取屏幕宽度的一半
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int screenWidthHalf = displayMetrics.widthPixels / 2;

        // 根据视频的宽高比计算视频的高度
        int videoHeight = (int) (screenWidthHalf / videoAspectRatio);

        // 设置 VideoView 的宽高
        ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
        layoutParams.width = screenWidthHalf;
        layoutParams.height = videoHeight;
        videoView.setLayoutParams(layoutParams);

    }

    private void copyFile(File src, File dst) throws IOException {
        try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}

/**
 * post函数可以确保视图布局完成之后再去执行操作，避免在视图布局未完成时获取到不正确的布局参数
 * <p>
 * Handler时Andriod中用于与线程通信的根据
 * 它允许你将Runnable对象放入到消息对了，在未来的时间点在与Handler关联的线程上执行
 * 他通常用来更新UI，因为他可以在主线程(UI线程)上执行代码
 * <p>
 * Handler时Andriod中用于与线程通信的根据
 * 它允许你将Runnable对象放入到消息对了，在未来的时间点在与Handler关联的线程上执行
 * 他通常用来更新UI，因为他可以在主线程(UI线程)上执行代码
 * <p>
 * Handler时Andriod中用于与线程通信的根据
 * 它允许你将Runnable对象放入到消息对了，在未来的时间点在与Handler关联的线程上执行
 * 他通常用来更新UI，因为他可以在主线程(UI线程)上执行代码
 */

/**
 * Handler时Andriod中用于与线程通信的根据
 * 它允许你将Runnable对象放入到消息对了，在未来的时间点在与Handler关联的线程上执行
 * 他通常用来更新UI，因为他可以在主线程(UI线程)上执行代码
 */